#include "File.h"

void file::write_ppm(char* filename, unsigned char* data, int w, int h) {

	 FILE* pFile;
	 char header[20];

	 pFile = fopen(filename, "wb");

	 // write "P6"
	 fwrite("P6\n", 3, 1, pFile);

	 // write "width height"
	 sprintf(header, "%d %d\n", w, h);
	 fwrite(header, strlen(header), 1, pFile);

	 // writeh "255"
	 fwrite("255\n", 4, 1, pFile);

	 // write rgba data
	 fwrite(data, w*h*3, 1, pFile);

	 fclose(pFile);
}

void file::ReleaseBinaryStream(const void *buffer) {
	delete [] buffer;
}

void * file::LoadBinaryStream(const char *filename, unsigned int *size) {

	FILE *file = fopen(filename, "rb");
	if ( file==NULL )
		return NULL;

	unsigned int file_size = 0;

	fseek(file, 0, SEEK_END);
	file_size = ftell(file);
	fseek(file, 0, SEEK_SET);
	unsigned char *buffer = new unsigned char[file_size];
	
	if ( buffer==NULL )
	{
		fclose(file);
		return NULL;
	}

	fread(buffer, file_size, 1, file);
	fclose(file);

	if ( size ) *size = file_size;

	return buffer;
}